package com.q3d.demo.svc.hello.fsguid.manager;

import com.alibaba.fastjson2.JSON;
import com.baidu.fsg.uid.impl.DefaultUidGenerator;
import com.q3d.demo.common.lib.fsguid.dto.FsgUidDto;
import com.q3d.demo.common.lib.fsguid.model.FsgUidModel;
import com.q3d.demo.common.lib.service.exception.ServiceException;
import com.q3d.demo.common.lib.service.response.ResponseStatus;

import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component /** 注入组件 */
/**
 * @author 叶湘 ( weixin:yexiang841, email:yexiang841@qq.com )
 */
public class FsgUidManager {

    @Autowired
    protected DefaultUidGenerator uidGenerator;

    @Autowired
    protected ModelMapper modelMapper;

    /**
     * 使用百度官方库生成一个全局唯一的 uid
     * 
     * @return Long
     * @throws UidGenerateException
     */
    public Long getUid() {
        long uid = uidGenerator.getUID();
        return Long.valueOf(uid);
    }

    /**
     * 使用百度官方库生成一个全局唯一的 uid
     * 
     * @return FsgUidDto
     * @throws UidGenerateException
     */
    public FsgUidDto getUidR1Dto() {
        long uid = uidGenerator.getUID();
        FsgUidDto fsgUidDto = this.parse(uid);
        return fsgUidDto;
    }

    /**
     * 使用百度官方库解析一个 uid
     *
     * @param uid
     * @return FsgUidDto，含解析后的 JSON 字符串
     */
    public FsgUidDto parse(long uid) {
        String stringUidInfo = uidGenerator.parseUID(uid);
        FsgUidModel uidModel = JSON.parseObject(stringUidInfo, FsgUidModel.class);
        if (uidModel == null) {
            throw new ServiceException(ResponseStatus.BAD_REQUEST_PARAM_VALID_ERROR,
                    "Parse_Internal_Uid_Failed");
        }
        FsgUidDto fsgUidDto = modelMapper.map(uidModel, FsgUidDto.class);
        return fsgUidDto;
    }

    public static void main(String[] args) {
        System.out.println("");
        String stringUid = "{\"UID\":\"2373134117266284545\",\"timestamp\":\"2022-05-25 09:21:33\",\"workerId\":\"35\",\"sequence\":\"1\"}";
        System.out.println("原始字符串                : " + stringUid);
        System.out.println("");
        FsgUidModel fsgUidModel = JSON.parseObject(stringUid, FsgUidModel.class);
        System.out.println("fsgUidModel.toString()   : " + fsgUidModel);
        System.out.println("fsgUidModel.toJSON()     : " + JSON.toJSONString(fsgUidModel));
        System.out.println("");
        FsgUidDto fsgUidR1Dto = (new ModelMapper()).map(fsgUidModel, FsgUidDto.class);
        System.out.println("fsgUidR1Dto.toString()   : " + fsgUidR1Dto);
        System.out.println("fsgUidR1Dto.toJSON()     : " + JSON.toJSONString(fsgUidR1Dto));
    }
}